package com.mrx.example.controller;

import com.mrx.example.dao.EmpDao;
import com.mrx.example.model.Emp;
import com.mrx.example.model.PostBody;
import com.mrx.example.model.Result;
import com.mrx.example.servlet.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "获取员工信息 API", value = "/emp")
public class EmpController extends BaseServlet {

    private static final EmpDao dao = new EmpDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String dId = req.getParameter("did");
        String id = req.getParameter("id");
        if (allNull(dId, id)) {
            send404ModelResponse(resp, Result.E404);
        } else if (dId != null) {
            sendModelResponse(resp, dao.findEmpsByDeptId(dId));
        } else {
            sendModelResponse(resp, dao.findEmpById(id));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String dId = req.getParameter("did");
        PostBody res = getPostBody(req);

        // 如果 部门 id 或 postBody 为空 或 postBody 不含 emp
        if (hasBlankOrNull(dId) || res.hasNull() || res.dataNotContains("emp")) {
            send404ModelResponse(resp, Result.E404);
        } else {
            Emp emp = res.getJavaObjectFromJSON("emp", Emp.class);
            sendModelResponse(resp, dao.addEmp(emp));
        }

    }
}
